<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <div class="title">
      <el-tag>操作步骤说明：</el-tag>
      <el-tag>第一步：点击“生成本级汇总综表数据”生成本级综合表</el-tag>
      <el-tag>第二步：点击本页面上报按钮，将本级综合表报送上级单位</el-tag>
    </div>
    <lb-table
      :column="tableData.column"
      :data="tableData.data"
      border
      :height="620"
      pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
    >
    </lb-table>
    <component
      :is="modelName"
      :id="id"
      :visible.sync="show"
      @close="close"
    ></component>
  </lb-layout>
</template>

<script>
import { getInfo } from "@/api/login";
import {
  gettobesummarizedlist,
  deleteLedger,
  reportLedger,
  getLedgermodify,
} from "@/api/standingbook/newstandingbook.js";

import operate from "@/views/work/accounts/report/components/operate.vue";
export default {
  name: "",
  components: {
    operate,
  },
  dicts: ["ledger_status"],
  data() {
    return {
      //弹窗
      id: "",
      modelName: "",
      show: false,
      deptId: null,
      deptLevel: null,
      apsForm: {
        formRef: "form",
        labelWidth: "auto",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            year: {
              label: "年份:",
              typeName: "el-date-picker",
              type: "year",
              size: "small",
              placeholder: "选择年份",
              "value-format": "yyyy",
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            {
              label: "生成本级汇总综表数据",
              type: "primary",
              typeName: "el-button",
              plain: true,
              size: "small",
              icon: "el-icon-plus",
              click: () => this.showModel("operate"),
            },
            {
              label: "全年",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-s-data",
              click: this.handlerAllyear,
            },
          ],
        },
      },
      currentPage: 1,
      pageSize: 20,
      total: 0,
      tableData: {
        column: [
          {
            prop: "year",
            label: "年度",
            width: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "organizationName",
            label: "报送单位",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let that = this;
              let name = scope.row.organizationName;
              let type = scope.row.summeryTable === 0 ? "2" : "1"; // 0 不是汇总数据 1是汇总数据
              let a = (
                <router-link
                  to={
                    "/work/standbook/reports/collect?deptId=" +
                    scope.row.deptId +
                    "&year=" +
                    scope.row.year +
                    "&month=" +
                    scope.row.month +
                    "&type=" +
                    type +
                    "&id=" +
                    scope.row.id
                  }
                  class="link-type"
                >
                  {name}
                </router-link>
              );
              return <div>{a}</div>;
            },
          },
          {
            prop: "ledgerStatus",
            label: "状态",
            width: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.ledger_status}
                    value={scope.row.ledgerStatus}
                  />
                </div>
              );
            },
          },
          {
            prop: "",
            label: "填报日期",
            width: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let that = this;
              let a = scope.row.year ?? "";
              let b = scope.row.month ?? "";
              let c = a + b;
              return h("div", c);
            },
          },
          {
            prop: "createTime",
            label: "创建时间",
            width: 180,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "updateTime",
            label: "更新时间",
            width: 180,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "ledgerEmployee",
            label: "审核人",
            // minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            label: "操作",
            width: 280,
            fixed: "right",
            render: (h, scope) => {
              let that = this;
              let a, b, c, g;
              let ledgerStatus = scope.row.ledgerStatus; // 台账申报状态
              let disabledFlage = that.deptLevel == 2 ? true : false;
              switch (ledgerStatus) {
                case 0:
                  a = (
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-upload2"
                      disabled={disabledFlage}
                      onClick={() => {
                        if (that.deptLevel == 2) {
                          // 最高级直接将数据导出（未做）
                          /* that.$message.success("已上报!"); */
                        } else {
                          that.reportGo(scope.row.id);
                        }
                      }}
                    >
                      上报
                    </el-button>
                  );
                  break;
                case 3:
                  g = (
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-check"
                      class="text-danger"
                      onClick={() => {
                        that.checkBackOk(scope.row);
                      }}
                    >
                      确认退回
                    </el-button>
                  );
                  break;
                // c = (
                //   <el-button
                //     type="text"
                //     size="small"
                //     icon="el-icon-delete"
                //     onClick={() => {
                //       that.handlerDelete(scope.row);
                //     }}
                //     class="text-danger"
                //   >
                //     删除
                //   </el-button>
                // );
              }
              b = (
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-view"
                  onClick={() => {
                    that.$router.push({
                      name: "standingbookCollect",
                      query: {
                        deptId: scope.row.deptId,
                        year: scope.row.year,
                        month: scope.row.month,
                        type: scope.row.summeryTable === 0 ? "2" : "1", // 0 不是汇总数据 1是汇总数据
                        id: scope.row.id,
                        createTime: scope.row.createTime,
                        statisticLeader: scope.row.statisticLeader,
                        unitLeader: scope.row.unitLeader,
                        createTime: scope.row.createTime,
                      },
                    });
                  }}
                >
                  查看
                </el-button>
              );
              return (
                <div style="display: flex;align-items: center;justify-content: flex-start;">
                  {a}
                  {b}
                  {c}
                  {g}
                </div>
              );
            },
          },
        ],
        data: [],
      },
    };
  },
  created() {
    // this.deptId = this.$store.state.user.deptId;
    // this.deptLevel = this.$store.state.user.deptLevel;
    this.getDeptLevel();
  },
  mounted() {
    // setTimeout(() => {
    //   this.handlerSearchDetail();
    // }, 200);
  },
  methods: {
    async getDeptLevel() {
      const res = await getInfo();
      this.deptLevel = res.user.deptLevel;
      this.deptId = res.user.deptId;
      await this.handlerSearchDetail();
    },
    async initData(data) {
      let that = this;
      let query = {
        ...data,
      };
      query.pageNum = that.currentPage;
      query.pageSize = that.pageSize;
      that.$store.commit("app/updateApiCount", "add");
      await gettobesummarizedlist(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res?.rows ?? [];
          that.total = res?.total ?? 0;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 搜索
    handlerSearchDetail() {
      const { year, ...other } = this.$refs?.form?.getFieldsValue();
      const data = {
        ...other,
      };
      if (year) {
        data.year = year + "年";
      }
      data.deptId = this.deptId;
      this.initData(data);
    },
    handlerAllyear() {
      // let time = new Date().getFullYear();
      // this.$refs?.form?.setFieldValue("year", time.toString());
      // this.pageSize = 12;
      // setTimeout(() => {
      //   this.handlerSearchDetail();
      // }, 200);
      this.$router.push({
        name: "reportDetail",
        query: {
          type: 1,
        },
      });
    },
    // 重置
    handleReset() {
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    reportGo(id) {
      let params = {
        ledgerIds: [],
      };
      params.ledgerIds.push(id);
      const text = "是否确认上报" + "该条数据" + "？";
      this.$modal
        .confirm(text)
        .then(() => {
          this.requestReport(params);
        })
        .catch(() => {
          this.$message({
            message: "取消",
          });
        });
    },
    //上报请求
    requestReport(params) {
      reportLedger(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            this.handlerSearchDetail();
            return false;
          }
          this.$message.success("已上报!");
          this.handlerSearchDetail();
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    handlerDelete(row) {
      let that = this;
      let id = row.id;
      const text = "是否确认删除" + (row?.name ?? "该条数据") + "？";
      this.$modal
        .confirm(text)
        .then(() => {
          that.delectRequest(id);
        })
        .catch(() => {
          that.$message({
            message: "取消删除",
          });
        });
    },
    delectRequest(id) {
      let that = this;
      deleteLedger(id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            this.handlerSearchDetail();
            return false;
          }
          that.$message.success("已删除!");
          that.handlerSearchDetail();
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 确认退回
    checkBackOk(row) {
      let id = row.id;
      let params = {
        ledgerIds: [],
      };
      params.ledgerIds.push(id);
      const text = "是否确认退回该条数据" + "？";
      this.$modal
        .confirm(text)
        .then(() => {
          this.requestModify(params);
        })
        .catch(() => {
          this.$message({
            message: "取消退回",
          });
        });
    },
    requestModify(params) {
      getLedgermodify(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            this.handlerSearchDetail();
            return false;
          }
          this.$message.success("已退回!");
          this.handlerSearchDetail();
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 弹窗
    showModel(name, params) {
      this.modelName = name;
      this.id = params?.id || "";
      setTimeout(() => {
        this.show = true;
      }, 200);
    },
    close(status) {
      this.show = false;
      setTimeout(() => {
        if (status) this.handlerSearchDetail();
      }, 200);
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .title {
  .el-tag {
    margin-right: 10px !important;
    margin-bottom: 20px;
  }
}
</style>
